function base64ToArrayBuffer(base64) {
    const binary_string = window.atob(base64);
    const len = binary_string.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

function arrayBufferToBase64(arrayBuffer) {
    const uint8Array = new Uint8Array(arrayBuffer);
    let binary = '';
    uint8Array.forEach((byte) => {
        binary += String.fromCharCode(byte);
    });
    return btoa(binary);
}

function stringToArrayBuffer(str) {
    const encoder = new TextEncoder();
    return encoder.encode(str).buffer;
}

const rawKey = stringToArrayBuffer('HlC#~PKyTAL5KGBK')
let iv = stringToArrayBuffer('MJKVNGHFJTURLMDF');

// 导入密钥，返回值为 Promise resolve 的 CryptoKey
function useImportSecretKey() {
    return window.crypto.subtle.importKey("raw", rawKey, 'AES-CBC', true, [
        "encrypt",
        "decrypt",
    ]);
}

/**
 * info 需要加密的信息
*/
export async function useAesCbcEncrypt(info) {
    const encoded = stringToArrayBuffer(info) // 获取将 string 转成 arrayBuffer 格式的字符串
    const key = await useImportSecretKey() //获取密钥对象
    const encryptText = await window.crypto.subtle.encrypt(
        {
            name: "AES-CBC",
            iv: iv,
        },
        key,
        encoded,
    )
    return arrayBufferToBase64(encryptText)
}

// 解密
export async function useAesDecrypt(base64) {
    try {
        const encryptedArrayBuffer = base64ToArrayBuffer(base64)
        const key = await useImportSecretKey()
        const decryptedData = await crypto.subtle.decrypt({ name: "AES-CBC", iv: iv }, key, encryptedArrayBuffer)
        // 将ArrayBuffer转换为Uint8Array
        const decryptedUint8Array = new Uint8Array(decryptedData);
        // 将Uint8Array转换为字符串
        const decryptedString = new TextDecoder('utf-8').decode(decryptedUint8Array);
        console.log('解密后的数据:', decryptedString);
    } catch (error) {
        console.log(error)
    }
}